<template>
  <div class="about-master-container">
    <base-breadcrumb :breadcrumb="!isAudit">
      <a-form-model
        ref="RuleForm"
        :model="formData"
        :rules="rules"
      >
        <a-card
          v-loading="loading"
          :bordered="false"
        >
          <title-name title="基本信息" />
          <a-row>
            <a-col span="8">
              <a-form-model-item label="编号">
                <BaseInput
                  v-model="formData.code"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <!-- <a-col span="8">
              <a-form-model-item
                label="所属分公司"
                prop="branchComId"
              >
                <SelectSubCompany
                  ref="selectSubCompany"
                  v-model="formData.branchComId"
                  :disabled="state == 3"
                  placeholder="请选择"
                  @change="getBranchComId"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="项目名称"
                prop="projectId"
              >
                <SelectProject
                  ref="selectProject"
                  v-model="formData.projectId"
                  placeholder="请选择"
                  :form="formData"
                  :is-clear="id == ''"
                  :disabled="state == 3"
                  key-value="branchComId"
                  @change="getProName"
                />
              </a-form-model-item>
            </a-col> -->
            <a-col span="16">
              <a-form-model-item
                label="所属单位"
                prop="projectId"
              >
                <OrgTreeSelect
                  v-model="formData.projectId"
                  :disabled="state == 3"
                  is-auto-select-first
                  @select="setProject"
                />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="甲方名称">
                <BaseInput
                  v-model="formData.name"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="项目业态">
                <BaseInput
                  v-model="formData.formats"
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card
          v-loading="loading"
          :bordered="false"
        >
          <title-name title="材料及供应商信息" />
          <a-row>
            <a-col :span="8">
              <a-form-model-item
                label="材料种类"
                prop="material"
              >
                <BaseInput
                  v-model="formData.material"
                  :disabled="state == 3"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="甲方规定备选品牌"
                prop="spareBrand"
              >
                <BaseInput
                  v-model="formData.spareBrand"
                  :disabled="state == 3"
                />
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item
                label=""
                prop="tableData"
              >
                <div class="table-operator">
                  <div class="pub-table-action-btn">
                    <a-button
                      v-if="state != 3"
                      type="primary"
                      @click="handleCheckUser"
                    >
                      新增供应商
                    </a-button>
                  </div>
                </div>
                <a-table
                  ref="table"
                  :scroll="{ x: 1376 }"
                  :loading="tableLoading"
                  :pagination="state != 1 ? false : pagination"
                  :columns="tableColumns"
                  :data-source="formData.tableData"
                >
                  <div
                    slot="type"
                    slot-scope="text, record, index"
                  >
                    <template>
                      <span>{{ text == '0' ? '否' : '是' }}</span>
                    </template>
                  </div>
                  <div
                    slot="operation"
                    slot-scope="text, record, index"
                    class="pub-table-list-action"
                  >
                    <template>
                      <span @click="() => handleEdit(record, index)">编辑</span>
                      <span @click="handleSure(record, index)">删除</span>
                    </template>
                  </div>
                </a-table>

                <pagination
                  v-if="state != 1"
                  v-model="pageNo"
                  :total="totalSize"
                  :page-size.sync="pageSize"
                  @change="handlePageChange"
                  @showSizeChange="showSizeChange"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card
          v-if="state == 3 && formData.status==2"
          v-loading="loading"
          :bordered="false"
        >
          <title-name title="甲方评价内容" />
          <a-row>
            <a-col span="8">
              <a-form-model-item label="供货质量">
                <a-select
                  v-model="formData.quality"
                  disabled
                >
                  <a-select-option
                    v-for="item in qualitydata"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="供货及时性">
                <a-select
                  v-model="formData.timeliness"
                  disabled
                >
                  <a-select-option
                    v-for="item in timelinessdata"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="24">
              <a-form-model-item label="运维评价（设备类材料）">
                <BaseTextarea
                  v-model="formData.appraise"
                  :max-length="10000"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="评价人">
                <BaseInput
                  v-model="formData.ownerName"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="评价时间">
                <BaseInput
                  v-model="formData.updateTime"
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form-model>

      <div class="pub-header-btn page-btn-right-top">
        <a-button
          v-if="state == 1"
          :loading="loading"
          type="primary"
          @click="onAdd"
        >
          提交
        </a-button>
        <a-button
          v-if="state == 2"
          :loading="loading"
          type="primary"
          @click="submit"
        >
          提交
        </a-button>
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>

      <a-modal
        v-if="checkShow"
        title="合作供应商信息"
        :visible="checkShow"
        width="60%"
        @cancel="clearUser"
      >
        <a-form-model
          ref="modelRuleForm"
          :model="formModal"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :rules="modalRules"
        >
          <a-row>
            <a-col span="12">
              <a-form-model-item
                label="合作供应商名称"
                prop="supplierName"
              >
                <a-select
                  v-model="formModal.supplierId"
                  class="selectSearch"
                  placeholder="请选择"
                  :filter-option="false"
                  :not-found-content="supLoad ? undefined : null"
                  :loading="supLoad"
                  :show-search="true"
                  @search="handleSearch"
                  @change="getCode"
                >
                  <a-icon
                    slot="suffixIcon"
                    type="search"
                    style="transform:none !important"
                  />
                  <a-spin
                    v-if="supLoad"
                    slot="notFoundContent"
                    size="small"
                  />
                  <a-select-option
                    v-for="item in supplierData"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="12">
              <a-form-model-item
                label="是否为甲指供应商"
                prop="type"
              >
                <a-select
                  v-model="formModal.type"
                  placeholder="请选择"
                >
                  <a-select-option
                    v-for="item in isData"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="24">
              <a-form-model-item
                label="合作供应商供应材料品牌"
                prop="materialBrand"
              >
                <BaseInput v-model="formModal.materialBrand" />
              </a-form-model-item>
            </a-col>
            <a-col span="24">
              <a-form-model-item
                label="合同关键条款"
                prop="concart"
              >
                <BaseTextarea
                  v-model="formModal.concart"
                  :max-length="10000"
                />
              </a-form-model-item>
            </a-col>
            <a-col span="24">
              <a-form-model-item label="备注">
                <BaseInput v-model="formModal.remark" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>

        <template slot="footer">
          <a-button @click="clearUser">
            取消
          </a-button>
          <a-button
            :loading="bindLoading"
            type="primary"
            @click="submitUser"
          >
            提交
          </a-button>
        </template>
      </a-modal>
    </base-breadcrumb>
  </div>
</template>

<script>
import { planAddFile, planFileList, planFileListDel, planListDetail, print } from '@/api/material/procurement/plan'
import {
  getCustomerSupplierBrandById,
  updateSelectiveSupplierBrand,
  getPageCustomerSupplierInfo,
  insertSelectiveSupplierBrand,
  updateInfoByPrimaryKeySelective,
  querySupplierList,
  deleteInFoByPrimaryKey,
  querySupplierIdList,
  getProjectInfo,
  insertInfo,
  getTotalScore
} from '@/api/complaint/satisfactionsurvey.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import debounce from 'lodash/debounce'
import { treeUpdate } from '@/api/technology'

export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject
  },
  props: {
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    this.handleSearch = debounce(this.handleSearch, 800)
    return {
      id: '',
      pageNo: 1,
      qualitydata: [
        {
          id: '1',
          name: '优质'
        },
        {
          id: '2',
          name: '合格'
        },
        {
          id: '3',
          name: '不合格	'
        }
      ],
      timelinessdata: [
        {
          id: '1',
          name: '及时'
        },
        {
          id: '2',
          name: '不及时'
        }
      ],
      pageSize: 10,
      totalSize: 0,
      key: '1',
      supLoad: false,
      checkShow: false,
      bindLoading: false,
      loading: false,
      state: Number(this.$route.query.state),
      isSubmit: false,
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据` //分页中显示总的数据
      },
      statuCode: '3',
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      // row: this.$route.query.row,
      formModal: {},
      modalRules: {
        supplierName: { required: true, message: '请选择合作供应商名称', trigger: 'change' },
        type: { required: true, message: '请选择是否为甲指供应商', trigger: 'change' },
        materialBrand: { required: true, message: '请输入合作供应商供应材料品牌', trigger: 'blur' },
        concart: { required: true, message: '请输入合同关键条款', trigger: 'blur' }
      },
      tableColumns: [
        {
          title: '合作供应商名称',
          dataIndex: 'supplierName',
          width: 160
        },
        {
          title: '是否为甲指供应商',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' },
          width: 220
        },
        {
          title: '合作供应商供应材料品牌',
          dataIndex: 'materialBrand',
          width: 160
        },
        {
          title: '合同关键条款',
          width: 160,
          dataIndex: 'concart'
        },
        {
          title: '备注',
          width: 160,
          dataIndex: 'remark'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 200,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      tableData: [],
      formData: {
        formats: '',
        tableData: [],
        branchComId: '',
        projectId: '',
        projectName: ''
      },
      rules: {
        projectId: { required: true, message: '请选择项目名称', trigger: 'change' },
        branchComId: { required: true, message: '请选择所属分公司', trigger: 'change' },
        material: { required: true, message: '请输入材料种类', trigger: 'blur' },
        spareBrand: { required: true, message: '请输入甲方规定备选品牌', trigger: 'blur' },
        tableData: { required: true, message: '请选择供应商', trigger: 'blur' }
      },
      mode: this.$route.query.pageTyp === 'add' ? 'add' : 'edit',
      projectLoading: false,
      planAddFile: planAddFile(),
      planFileList: planFileList(),
      planFileListDel: planFileListDel(),
      treeLoading: false,
      ownerData: [],
      idList: null,
      checkType: 'add',
      tableLoading: false,

      checkIndex: null,
      supplierData: [],

      isData: [
        {
          value: '0',
          label: '否'
        },
        {
          value: '1',
          label: '是'
        }
      ]
    }
  },

  watch: {
    formData: {
      deep: true,
      handler() {
        this.$checkRequireItem()
      }
    },
    //    'form.tableData'() {
    //   if (this.state != 0 ) {
    //     this.$nextTick(() => {
    //       this.$refs.RuleForm?.validateField('tableData')
    //     })
    //   }
    // },
    isAudit: {
      // 是否作为审批详情
      immediate: true,
      handler(val) {
        if (val) {
          this.state = 3
        }
      }
    }
  },
  created() {
    if (this.state == 3) {
      this.tableColumns.splice(5, 1)
    }
  },
  mounted: function () {
    if (this.state != 1) {
      this.id = this.$route.query.id
      this.list()
      this.getDetail()
      this.isSubmit = true
    }
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleSearch(v) {
      if (v == '') {
        return false
      }
      this.supLoad = true
      this.supplierData = null
      querySupplierList({ supplierName: v, idList: this.idList }).then((res) => {
        if (res.code == 200) {
          this.supplierData = res.data
          this.supLoad = false
        }
      })
    },

    getCode(v) {
      this.formModal.supplierName = this.supplierData.find((item) => item.id == v).name
    },
    handleEdit(record, index) {
      this.supLoad = true
      this.checkType = 'edit'
      this.checkShow = true
      querySupplierList({ supplierName: record.supplierName, idList: this.idList }).then((res) => {
        if (res.code == 200) {
          this.supplierData = res.data
          this.formModal = record
          this.checkIndex = index

          this.supLoad = false
        }
      })
    },
    handleSure(record, index) {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '是否删除?',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          if (that.state == 2) {
            that.tableLoading = true
            return deleteInFoByPrimaryKey(record.id)
              .then((res) => {
                that.tableLoading = false
                that.$message.success('删除成功！')
                that.list()
                that.$refs.table.refresh(true)
              })
              .catch((err) => {
                that.tableLoading = false
                console.log(err)
              })
          } else {
            // return () => {
            that.formData.tableData.splice(index, 1)
            // }
          }
        }
      })
    },
    initCode() {
      if (this.state == 1) {
        console.log(this.formData)
        let codedata = this.formData.tableData.map((item) => (item = item.supplierId))
        if (codedata.length != 0) {
          this.idList = codedata
        }
      } else {
        querySupplierIdList({ brandId: this.id }).then((res) => {
          if (res.data) {
            this.idList = res.data
          }
        })
      }
    },
    handleCheckUser() {
      this.initCode()
      this.checkShow = true
      this.formModal = {
        ...this.formModal,
        type: '0'
      }
    },
    clearUser() {
      this.checkShow = false
      this.checkType = 'add'
      this.checkIndex = null
      this.supplierData = null
      this.formModal = {}
    },
    submitUser() {
      this.$refs.modelRuleForm.validate((valid) => {
        if (valid) {
          if (this.state == 2) {
            if (this.checkType == 'edit') {
              this.tableLoading = true
              updateInfoByPrimaryKeySelective({ ...this.formModal, brandId: this.id }).then((res) => {
                this.list()
                this.tableLoading = false
                if (res.code == 200) {
                  this.$message.success('修改成功')
                }
              })
            } else {
              this.tableLoading = true
              insertInfo({ ...this.formModal, brandId: this.id }).then((res) => {
                this.list()
                this.tableLoading = false
                if (res.code == 200) {
                  this.$message.success('新增成功')
                }
              })
            }
          } else {
            if (this.checkType == 'add') {
              this.formData.tableData.push({
                ...this.formModal
              })
              this.totalSize = Number(this.tableData.length)
            } else {
              this.formData.tableData.splice(this.checkIndex, 1, this.formModal)
            }
          }
          this.$refs.RuleForm?.validateField('tableData')
          this.clearUser()
        }
      })
    },
    list() {
      const searchData = {
        pageSize: this.pageSize,
        pageNum: this.pageNo,
        param: {
          brandId: this.id
        }
      }
      this.tableLoading = true
      getPageCustomerSupplierInfo(searchData).then((resp) => {
        if (resp.code == 200) {
          this.formData = { ...this.formData, tableData: resp.data.list }
          this.totalSize = resp.data.total
        }
        this.tableLoading = false
      })
    },
    handlePageChange(pageNo, pageSize) {
      this.pageNo = pageNo
      this.list()
      this.selectedRowKeys = []
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
      this.list()
    },
    handleChange(e, v) {
      this.formData[v.code] = e
      v.pickNumber = e
      getTotalScore({ ...this.formData, tableData: null }).then((res) => {
        this.formData.totalSorce = res.data
      })
    },
    // getBranchComId(value) {
    //   const data = this.$refs.selectSubCompany.getValueName(value)
    //   if (data) {
    //     this.formData.branchComName = data
    //   }
    // },
    // getProName(value) {
    //   if (this.state != 3) {
    //     const projectName = this.$refs.selectProject.getValueName(value)
    //     if (projectName) {
    //       this.formData.projectName = projectName
    //     }
    //     getProjectInfo(value).then((proResp) => {
    //       if (proResp.code == 200) {
    //         this.formData.formats = proResp.data.formats
    //         this.formData.name = proResp.data.constructionUnit
    //       }
    //     })
    //   }
    // },
    /**
     * @description: 设置分公司和项目信息
     * @param {object} val 选中数据
     * @return {void}
     */
    setProject(val) {
      if (val && val.length > 0) {
        const value = val[1]?.projectId
        this.formData.branchComId = val[0]?.orgId
        this.formData.branchComName = val[0]?.orgName
        this.formData.projectName = val[1]?.projectName
        getProjectInfo(value).then((proResp) => {
          if (proResp.code == 200) {
            this.formData.formats = proResp.data.formats
            this.formData.name = proResp.data.constructionUnit
          }
        })
      }
    },
    getTabChange(e) {
      this.$checkRequireItem()
    },
    getDetail() {
      this.loading = true
      getCustomerSupplierBrandById({ id: this.$route.query.id }).then((res) => {
        this.loading = false
        this.formData = { ...this.formData, ...res.data }
      })
    },
    // 编辑新增时候的保存
    onAdd() {
      this.$refs.RuleForm.validate((valid) => {
        if (valid) {
          this.$submitConfirm(async () => {
            this.loading = true
            insertSelectiveSupplierBrand({ ...this.formData, infoList: this.formData.tableData.length != 0 ? this.formData.tableData : null }).then((res) => {
              if (res.code == 200) {
                this.loading = false
                this.$message.success('提交成功')
                this.$multiTab.close(this.$route.fullpath)
              } else {
                this.loading = false
              }
            })
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    // 编辑新增时候的保存
    submit() {
      this.$refs.RuleForm.validate((valid) => {
        if (valid) {
          this.$submitConfirm(async () => {
            this.loading = true
            updateSelectiveSupplierBrand({ ...this.formData, tableData: null, infoList: this.formData.tableData }).then((res) => {
              if (res.code == 200) {
                this.loading = false
                this.$message.success('提交成功')
                this.$multiTab.close(this.$route.fullpath)
              } else {
                this.loading = false
              }
            })
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.selectSearch {
  /deep/ svg {
    -webkit-transition: none;
    transform: none !important;
    transition: none;
  }
  /deep/.ant-select-open .ant-select-arrow-icon svg {
    -webkit-transition: none;
    transform: none !important;
    transition: none;
  }
}
</style>
